#!/bin/bash
# author: onion
# date: 2025年7月7日15:30:33
# description： 导出分布式表结构

CK_USERNAME=default
CK_PASSWORD=SinoTruk!@#456
CK_DBNAME=snc_aiops_performance
CLUSTER_NAME="cluster_3shards_1replicas"

CK_CLIEN="clickhouse-client --port 9000 --user ${CK_USERNAME} --password ${CK_PASSWORD} --database ${CK_DBNAME}"

# 获取表列表
all_tables=$(${CK_CLIEN} --query "show tables;")
tables_array=($all_tables)

# 计算表的数量
table_count=${#tables_array[@]}

# 显示表和数量
echo "要导出 ${table_count} 个表，如下："
for table in "${tables_array[@]}"; do
    echo "  - ${table}"
done

# 修正导出逻辑
> test.sql
> ck.sql
for table in "${tables_array[@]}";
do
    echo "正在处理表: ${table}..."

    # 获取原始建表语句
    create_sql=$(${CK_CLIEN} --query "show create table ${table};")

    # 修正ON CLUSTER位置
    if [[ ! $create_sql =~ "ON CLUSTER" ]]; then
        # 正确的位置：在表名后添加ON CLUSTER
        create_sql=$(echo "$create_sql" | sed "s/CREATE TABLE ${CK_DBNAME}.${table}/CREATE TABLE ${CK_DBNAME}.${table} ON CLUSTER ${CLUSTER_NAME}/g")
    fi

    echo "${create_sql};" >> test.sql
done

sed -i 's#\\n#\ #g' test.sql
sed -i 's#\\##g' test.sql

while read line; do
    echo "${line}" >> ck.sql
done < test.sql

rm -rf test.sql

echo "导出完成！共处理 ${table_count} 个表"
echo "最终文件已保存为 ck.sql，请执行：clickhouse-client --password ${CK_PASSWORD} -d ${CK_DBNAME} --multiquery < ck.sql"
echo "本脚本只处理了table，view需要编辑ck.sql手动处理"